package com.kun.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class RequestUtil {

    /**
     * 构造完整请求url（带参数）
     * @param url 请求url，形如：http://192.168.1.19
     * @param params 请求参数，key是参数名，value是参数值
     * @return 构造好的url，形如：http://192.168.1.19?name=mark&base=jinan
     */
    public static String buildUrl(String url, Map<String, String> params) throws UnsupportedEncodingException {

        StringBuilder urlBuilder = new StringBuilder(url);

        if (params != null) {
            Set<String> keySet = params.keySet();
            if (keySet.size()>0) {
                urlBuilder.append("?");

                for (String key : keySet) {
                    urlBuilder.append(key)
                            .append("=")
                            .append(URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name()))
                            .append("&");
                }

                urlBuilder.deleteCharAt(urlBuilder.length() - 1);
            }
        }

        return urlBuilder.toString();
    }



    /**
     * 发起GET请求（使用java原生方法）
     * @param url 请求路径
     * @param params 请求参数
     * @param headers 请求头
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        // 1.构造完整请求url（带参数）
        String fullUrl = buildUrl(url, params);
//        System.out.println("请求的地址"+fullUrl);

        // 2.打开连接
        HttpURLConnection conn = (HttpURLConnection) new URL(fullUrl).openConnection();

        // 3.设置请求方法为get
        conn.setRequestMethod("GET");

        // 4.设置请求头
        if (headers != null) {
            Set<String> headerKeys = headers.keySet();
            if (headerKeys.size()>0) {
                for (String headerKey : headerKeys) {
                    conn.setRequestProperty(headerKey, headers.get(headerKey));
                }
            }
        }

        // 5.获取响应状态码（非2开头状态码，认定请求失败）
        int statusCode = conn.getResponseCode();

        // 6.获取请求结果
        return getContent(conn.getInputStream());
    }

    /**
     * 读取InputStream
     */
    private static String getContent(InputStream inputStream) throws IOException {
        try (BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8.name()))) {

            String line;
            StringBuilder result = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        }
    }




}